package com.myminio.springbootminio.controller

import cn.hutool.json.JSONObject
import com.myminio.springbootminio.entity.RestResult
import com.myminio.springbootminio.service.MinIoService
import io.minio.messages.Bucket
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.springframework.http.MediaType
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.multipart.commons.CommonsMultipartFile
import java.util.*
import javax.annotation.Resource
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@Api("minio对象存储控制类")
@RestController
@CrossOrigin
@RequestMapping("/minio")
class MinioController {
    @Resource
    private lateinit var minioService:MinIoService

    @ApiOperation("获取所有存储对象命名空间")
    @GetMapping(value=["/getAllBucket"],produces = [MediaType.APPLICATION_JSON_VALUE])
    fun getAllBucket(@ApiParam(value = "是否显示包含的文件",name = "listObjs",required = true,defaultValue = "0")@RequestParam listObjs:Int):RestResult<JSONObject> = if(listObjs>0) minioService.getAllBucket(true) else minioService.getAllBucket(false)

    @ApiOperation("创建一个命名空间(文件夹)")
    @PostMapping("/createOneBucket")
    fun createOneBucket(@ApiParam(value = "命名空间名称",name="bucketName",required = true)@RequestParam  bucketName: String):Boolean = minioService.createBucket(bucketName)

    @ApiOperation("删除一个命名空间")
    @PostMapping("/delOneBucket")
    fun deleteBucket(@ApiParam(value = "命名空间名称",required = true)@RequestParam bucketName: String):Boolean = minioService.deleteBucket(bucketName)

    @ApiOperation("通过transferTo()上传文件")
    @PostMapping("/uploadToLocal")
    fun uploadToLocal(@RequestParam("file")file:MultipartFile):RestResult<String> = minioService.commonUploadFile(file)

    @ApiOperation("通过文件流上传文件")
    @PostMapping("/uploadToLocal2")
    fun uploadToLocal2(@RequestParam("file")file:MultipartFile):RestResult<String> = minioService.uploadByInputStream(file)


    @ApiOperation("上传文件")
    @PostMapping("/uploadToMinio")
    fun upload(@ApiParam(value="待上传文件",name="file")@RequestParam("file") file:MultipartFile, @ApiParam("待存储空间名称") @RequestParam bucketName: String): RestResult<String> = minioService.uploadFile(file)

    @ApiOperation("下载文件")
    @PostMapping("/download")
    fun download(@ApiParam(value = "存储空间名称",required = true)@RequestParam bucketName: String,@ApiParam(value = "文件名",required = true)@RequestParam fileName:String): RestResult<String> = minioService.downloadFile(bucketName, fileName)


    @ApiOperation("删除一个文件")
    @RequestMapping(value= ["/delFile"],method = [RequestMethod.GET,RequestMethod.POST])
    fun deleteFile(@RequestParam bucketName: String,@RequestParam fileName: String):RestResult<String> = minioService.deleteFile(bucketName,fileName)

}